package com.tianque.scgrid.service.record.config;

import com.tianque.scgrid.service.record.properties.ESConfigProperties;
import com.tianque.scgrid.service.record.util.ESClientUtil;
import org.apache.http.HttpHost;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;

/**
 * ES RestHttp 请求配置
 *
 * @author LiRui
 * @version 1.0
 */
@Configuration
@EnableConfigurationProperties(ESConfigProperties.class)
@ConditionalOnProperty(prefix = "es.client", name = "enable", havingValue = "true")
public class ESRestClientConfig {

    @Autowired
    private ESConfigProperties esConfigProperties;

    /**
     * HighLevelRestConfig
     *
     * @param
     * @return org.elasticsearch.client.RestClient
     * @author lirui
     */
    @Bean
    @ConditionalOnMissingBean(value = {RestHighLevelClient.class})
    public RestHighLevelClient restHighLevelClient() {
        // 如果有多个从节点可以持续在内部new多个HttpHost，参数1是IP，参数2是端口，参数3是通信协议
        final List<String> hostname = esConfigProperties.getHostname();
        Node[] nodes = new Node[hostname.size()];
        for (int i = 0; i < hostname.size(); i++) {
            final String host = hostname.get(i);
            String hostN = host.split(":")[0];
            //默认9200端口
            int port = Objects.isNull(host.split(":")[1]) ? 9300 : Integer.parseInt(host.split(":")[1]);
            nodes[i] = new Node(new HttpHost(hostN, port, "http"));
        }
        final RestClientBuilder builder = RestClient.builder(nodes);
        return new RestHighLevelClient(builder);
    }

    @Bean
    @ConditionalOnBean(RestHighLevelClient.class)
    public ESClientUtil esClientUtil(RestHighLevelClient restHighLevelClient) {
        return ESClientUtil.INITIALIZE(restHighLevelClient);
    }
}
